package cn.fl.risk.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.risk.condition.RskUsrCstRQueryCondition;
import cn.fl.risk.service.IRskUsrCstRService;
import cn.fl.risk.vo.RskUsrCstRVO;
import cn.fl.system.constant.SysLogConstant;
import net.sf.json.JSONArray;

/**
 * @Description: 催收员客户关系表 控制层
 */
@Controller
@RequestMapping("/risk/rskUsrCstR")
public class RskUsrCstRController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(RskUsrCstRController.class);

    /**
     * RskUsrCstR 服务层BEAN
     */
    @Autowired
    private IRskUsrCstRService rskUsrCstRService;

    /*********************
     * 到分配催收任务列表
     *********************/
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载到分配催收任务列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("risk/rskUsrCstR/rskUsrCstRList");
        return mav;
    }

    /********************
     * 分配催收任务客户列表
     ********************/
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initCstList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initCstList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        SysUsrQueryCondition qc = new SysUsrQueryCondition();
        String cstNm = request.getParameter("cstNm");
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setRlNm(cstNm);
        }
        page.setCondition(qc);
        BaseLogUtils.info(logger, "initCstList", "初始化RskUsrCstR列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.rskUsrCstRService.searchCstList(page);
        List<RskUsrCstRVO> list = (List<RskUsrCstRVO>) pager.getResultList();
        ListPageVO<RskUsrCstRVO> listPage = new ListPageVO<RskUsrCstRVO>(list, pager.getTotalCount());
        return listPage;
    }


    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载RskUsrCstR Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("risk/rskUsrCstR/rskUsrCstRModify");
        //this.prepare(request,mav);
        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载RskUsrCstR Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("risk/rskUsrCstR/rskUsrCstRModify");
        //this.prepare(request,mav);

        String id = request.getParameter("id");
        RskUsrCstRVO rskUsrCstRVO = this.rskUsrCstRService.selectById(Long.valueOf(id));
        mav.addObject("rskUsrCstRVO", rskUsrCstRVO);
        return mav;
    }

    //加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request, ModelAndView mav) {

    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initRskUsrCstRList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        RskUsrCstRQueryCondition qc = new RskUsrCstRQueryCondition();
        String cstNm = request.getParameter("cstNm");
        if (StringUtils.isNotEmpty(cstNm)) {
            qc.setCstNm(cstNm);
        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initRskUsrCstRList", "初始化RskUsrCstR列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.rskUsrCstRService.searchListPage(page);
        List<RskUsrCstRVO> list = (List<RskUsrCstRVO>) pager.getResultList();
        ListPageVO<RskUsrCstRVO> listPage = new ListPageVO<RskUsrCstRVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public DataResultVO removeRskUsrCstRByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeRskUsrCstRByIds", "删除RskUsrCstR数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            boolean success = this.rskUsrCstRService.removeByIds(idsList);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeRskUsrCstRByIds", "删除RskUsrCstR数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeRskUsrCstRByIds", "删除RskUsrCstR数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeRskUsrCstRByIds", "删除RskUsrCstR数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeRskUsrCstRByIds", "删除RskUsrCstR数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getRskUsrCstRById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getRskUsrCstRById", "获取RskUsrCstR数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            RskUsrCstRVO vo = this.rskUsrCstRService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getRskUsrCstRById", "获取RskUsrCstR数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getRskUsrCstRById", "获取RskUsrCstR数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getRskUsrCstRById", "获取RskUsrCstR数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getRskUsrCstRById", "获取RskUsrCstR数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addRskUsrCstR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        RskUsrCstRVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForRskUsrCstR(request);//获取参数
            Long id = this.rskUsrCstRService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "addRskUsrCstR", "新增RskUsrCstR数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addRskUsrCstR", "新增RskUsrCstR数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addRskUsrCstR", "新增RskUsrCstR数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增关系,分配任务
     */
    @RequestMapping(value = "/assignedTask.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addUsrCstR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "任务分配成功");
        RskUsrCstRVO entity = null;//获取参数

        String ids = request.getParameter("ids");//客户ID集合
        String usrId = request.getParameter("usrId");//用户ID
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("未找到客户信息");
            BaseLogUtils.info(logger, "addUsrCstR", "分配任务，新增用户客户关系，客户ID为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        if (StringUtils.isEmpty(usrId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("未找到用户信息");
            BaseLogUtils.info(logger, "addUsrCstR", "分配任务，新增用户客户关系，用户ID为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            entity = new RskUsrCstRVO();
            entity.setUsrId(Long.valueOf(usrId));
            entity.setCstIdList(idsList);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            boolean success = this.rskUsrCstRService.addR(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("任务分配失败");
                BaseLogUtils.info(logger, "modifyRskUsrCstR", "分配任务，新增RskUsrCstR数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "addRskUsrCstR", "分配任务，新增RskUsrCstR数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addRskUsrCstR", "分配任务，新增RskUsrCstR数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addRskUsrCstR", "分配任务，新增RskUsrCstR数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增关系，领取任务
     */
    @RequestMapping(value = "/collectTask.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object collectTask(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "任务领取成功");
        RskUsrCstRVO entity = null;//获取参数

        String ids = request.getParameter("ids");//客户ID集合
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("未找到客户信息");
            BaseLogUtils.info(logger, "collectTask", "领取任务，新增用户客户关系，客户ID为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            entity = new RskUsrCstRVO();
            entity.setUsrId(CurrentThreadContext.getCurrentUserId());
            entity.setCstIdList(idsList);
            boolean success = this.rskUsrCstRService.addR(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("任务领取失败");
                BaseLogUtils.info(logger, "collectTask", "领取任务，新增RskUsrCstR数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "collectTask", "领取任务，新增RskUsrCstR数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "collectTask", "领取任务，新增RskUsrCstR数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "collectTask", "领取任务，新增RskUsrCstR数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }


    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyRskUsrCstR(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        RskUsrCstRVO entity = null;
        try {
            entity = this.getRequestParamForRskUsrCstR(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyRskUsrCstR", "修改RskUsrCstR信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
                return result;
            }

            boolean success = this.rskUsrCstRService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyRskUsrCstR", "修改RskUsrCstR数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyRskUsrCstR", "修改RskUsrCstR数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyRskUsrCstR", "修改RskUsrCstR数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyRskUsrCstR", "修改RskUsrCstR数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private RskUsrCstRVO getRequestParamForRskUsrCstR(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String usrId = request.getParameter("usrId");//用户ID
        String cstId = request.getParameter("cstId");//客户ID

        //验证参数并赋值
        RskUsrCstRVO entity = new RskUsrCstRVO();
        //entity.setUsrId(usrId);//用户ID
        //entity.setCstId(cstId);//客户ID

//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            //entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
        }

        return entity;
    }
}

